package com.ft.user.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.ft.user.domain.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@Service
public class UserServiceImpl implements UserService {
	final String SERVICE_NAME="ft-platform-server";
	@Resource
	RestTemplate restTemplate;
	
	/* (non-Javadoc)
	 * @see com.ft.user.service.UserService#getList()
	 * @HystrixCommand中的fallbackMethod属性，是当该断路器处于断开状态时，所指定的方法将替代当前方法接受调用
	 */
	@SuppressWarnings("unchecked")
	@HystrixCommand(fallbackMethod = "fallbackSearchAll")
	@Override
	public List<User> getList() {
		return restTemplate.getForObject("http://"+SERVICE_NAME+"/user", List.class);
	}

	@HystrixCommand
	@Override
	public int updateNameById(String name, Long id) {
		MultiValueMap<String, Object> requestEntity = new LinkedMultiValueMap<>();
		requestEntity.add("id", id);
		requestEntity.add("name", name);
		return restTemplate.postForObject("http://"+SERVICE_NAME+"/user/updateNameById", requestEntity , Integer.class);
	}

	@Override
	public User save(User user) {
		// TODO Auto-generated method stub
		return null;
	}

	@SuppressWarnings("unused")
	private List<User> fallbackSearchAll() {
		 System.out.println("HystrixCommand fallbackMethod handle!");
		 List<User> ls = new ArrayList<User>();
		 User user = new User();
		 user.setName("TestHystrixCommand");
		 ls.add(user);
		 return ls;
	 }
}
